/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BASearchViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 06/08/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAUserSearchViewController.h"
#import "BARPCManager.h"
#import "BACollection.h"
#import "BARecord.h"
#import "BAUtils.h"
#import "BAFacet.h"
#import "BATerm.h"
#import "BALibrarySettings.h"
#import "BAFlyoutMenuViewController.h"
#import "BARecentSearchesDataSource.h"
#import "BACoverUrlAndAvailabilityMemoryCache.h"
#import "BAPatronSettings.h"
#import "BASearchBar.h"

#ifdef BA_LIBRARIAN_BUILD
#import "LBRPCManager.h"
#import "LBLibrarianSearchViewController.h"
#endif

#ifdef BA_IMF_BUILD
#import "IMFPackage.h"
#import "IMFSuggestedPackagePageViewController.h"
#endif

@class IMFSuggestedPackagePageViewController;

@interface BAUserSearchViewController ()<UIScrollViewDelegate> {
    BOOL shouldBeginEditing;
    NSMutableArray* filterDescriptionsBarButtons;
    NSMutableArray* filterDescriptionStrings;

    UIEdgeInsets currentInset;
    CGPoint currentOffset;
    CGPoint newOffset;
    BOOL searchResultHasImfPackages;
    BOOL isLibrarianAlmaSearchMore;
}

/*
 NB: make sure the name of this property doesn't hide
 searchResultsViewController property in UIViewController(UISearchDisplayControllerSupport)
 (see UIViewController.h) */
@property (strong, nonatomic) IBOutlet BASearchResultsViewController *baSearchResultsViewController;

@property (weak, nonatomic) IBOutlet UILabel *noResultsLabel;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingIndicator;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *revealFilterButtonsButtonWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *filterDescriptionsHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *filterDescriptionsContentWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchBarTralingSpace; //FIXME: bad name, is effectively the width of the Reveal Filters Button
@property (weak, nonatomic) IBOutlet UIView *performingSearchView;
@property (weak, nonatomic) IBOutlet UIView *startSearchView;
@property (weak, nonatomic) IBOutlet UILabel *startYourSearchLabel1;
@property (weak, nonatomic) IBOutlet UILabel *startYourSearchLabel2;
@property (weak, nonatomic) IBOutlet UIScrollView *filterDescriptionsScroller;
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchFilterButtonSelectionIndicatorXOffset;

@property (weak, nonatomic) IBOutlet UIImageView *filterDescriptionsSelectionIndicatorImage;
@property (strong, nonatomic) IBOutlet UIView *filterDescriptionsContent;

@property (weak, nonatomic) IBOutlet UIButton *largeFilterButton1;
@property (weak, nonatomic) IBOutlet UIButton *largeFilterButton2;
@property (weak, nonatomic) IBOutlet UIButton *largeFilterButton3;
@property (weak, nonatomic) IBOutlet UILabel *largeFilterButton1CountLabel;
@property (weak, nonatomic) IBOutlet UILabel *largeFilterButton2CountLabel;
@property (weak, nonatomic) IBOutlet UILabel *largeFilterButton3CountLabel;

@property (nonatomic, strong) NSString* searchQuery;
@property (nonatomic, assign) NSInteger searchOffset;
@property (nonatomic, strong) NSDictionary* searchQueryUserFilter;
@property (nonatomic, strong) NSDictionary* searchQueryLibrarianFilter;

@property (nonatomic, strong) BASearchResult* latestResult;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *filterButtonsHeight;
@property (weak, nonatomic) IBOutlet UIButton *revealFiltersButton;
@property (weak, nonatomic) IBOutlet UITableView *recentSearchesTableView;
@property (weak, nonatomic) IBOutlet UIView *filterDescriptionsBar;
@property (weak, nonatomic) IBOutlet UIView *filterButtonsContainer;

@property (weak, nonatomic) IBOutlet UIView *packageScrollViewContainer;
@property (nonatomic, strong) IMFSuggestedPackagePageViewController* packageViewer;

@property (weak, nonatomic) IBOutlet BASearchBar *searchBar;
@property (strong, nonatomic) IBOutlet BARecentSearchesDataSource *recentSearchesDataSource;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *recentSearchesBottomSpace;
//@property (strong, nonatomic) NSMutableArray* packageViewControllers;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *startSearchViewBottomSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *activityViewBottomSpace;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchContentTopConstraint;

@property (weak, nonatomic) IBOutlet UIView *mainContentView;

@property (nonatomic, assign) BOOL largeFilterBarHidden;
@property (nonatomic, assign) BOOL packagesHidden;

@property (weak, nonatomic) IBOutlet UIView *packageAndFilterButtonsContainerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *packageViewContainerHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *filterButtonsContainerHeight;


- (IBAction)revealFiltersButtonClicked:(id)sender;

@end

@implementation BAUserSearchViewController

-(void)commonInitUserSearchViewController
{
    filterDescriptionsBarButtons = [NSMutableArray new];
    filterDescriptionStrings = [NSMutableArray new];
    self.searchQueryLibrarianFilter = @{};
    self.searchQueryUserFilter = @{};
}

- (id)init
{
    self = [super init];
    if (self) {
        [self commonInitUserSearchViewController];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInitUserSearchViewController];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self commonInitUserSearchViewController];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    shouldBeginEditing = YES;
    //[self.recentSearchesTableView setScrollsToTop:NO];
    [self.filterDescriptionsScroller setScrollsToTop:NO];
    
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationCompletelyColored)
    
    //[self.baSearchResultsViewController setDelegate:self];
    [self.baSearchResultsViewController setBaSearchViewController:self];
    [self.baSearchResultsViewController setScrollViewDelegate:self];
    
    
    //This allows all pans on the entire view to act as scrollevents on the search
    [self.mainContentView addGestureRecognizer:self.baSearchResultsViewController.tableView.panGestureRecognizer];
    
    BA_LABEL_SET_FONT_REGULAR(self.noResultsLabel);
    BA_LABEL_SET_FONT_MEDIUM(self.startYourSearchLabel1);
    BA_LABEL_SET_FONT_REGULAR(self.startYourSearchLabel2);
    BA_LABEL_SET_FONT_REGULAR(self.largeFilterButton1CountLabel);
    BA_LABEL_SET_FONT_REGULAR(self.largeFilterButton2CountLabel);
    BA_LABEL_SET_FONT_REGULAR(self.largeFilterButton3CountLabel);
    
    [self addChildViewController:self.baSearchResultsViewController]; //setup navigation controller reference correctly
    
    
    [self hideRevealFiltersButton];
    [self hideFilterButtons:YES adjustOffset:YES animated:NO];
    [self hideFilterDescriptionsBar];
    self.filterButtonsHeight.constant = 0;
    //[self.filterDescriptionsBar setHidden:YES];
    
    self.performingSearchView.hidden=YES;

    self.filterDescriptionsContent.translatesAutoresizingMaskIntoConstraints=NO;

    [self.filterDescriptionsScroller addSubview:self.filterDescriptionsContent];
    NSDictionary* viewsdict = NSDictionaryOfVariableBindings(_filterDescriptionsContent);
    [self.filterDescriptionsScroller addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_filterDescriptionsContent]|" options:0 metrics:0 views:viewsdict]];
    [self.filterDescriptionsScroller addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_filterDescriptionsContent(42)]|" options:0 metrics:0 views:viewsdict]];
    
    [self setupCustomerColors:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupCustomerColors:) name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
    
#ifdef BA_IMF_BUILD
    if ([BALibrarySettings instance].isImfEnabled) {
        self.packageViewer = [IMFSuggestedPackagePageViewController new];
        [self addChildViewController:self.packageViewer];
        [self.packageScrollViewContainer addSubview:self.packageViewer.view];
        [BAUtils setViewToFillParent:self.packageViewer.view];
    }
#endif
    
    if ([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
        [self.searchBar setPlaceholder:@"Søg i materialer"];
    }
}

-(void)setupCustomerColors:(id)sender
{
    self.revealFiltersButton.backgroundColor = [[BALibrarySettings instance] getCustomerColorDark];
    self.largeFilterButton1.backgroundColor = [[BALibrarySettings instance] getCustomerColorDark];
    self.largeFilterButton2.backgroundColor = [[BALibrarySettings instance] getCustomerColorDark];
    self.largeFilterButton3.backgroundColor = [[BALibrarySettings instance] getCustomerColorDark];
    self.filterButtonsContainer.backgroundColor = [[BALibrarySettings instance] getCustomerColorNormal];
   
}

-(void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
    [self removeKeyboardObserver];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self enableUserInteraction];
    [self addKeyboardObserver];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self removeKeyboardObserver];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText   // called when text changes (including clear)
{
    if(![searchBar isFirstResponder]) {
        // user tapped the 'clear' button
        shouldBeginEditing = NO;
        [self clearSearchResultsAndHideFilters];
        self.startSearchView.hidden = NO;
        self.noResultsLabel.hidden = YES;
        [BARPCManager closeConnectionsForView:self];
        
    } else if ([searchText length]==0) {
        [self clearSearchResultsAndHideFilters];
        self.startSearchView.hidden = NO;
        self.noResultsLabel.hidden = YES;
        [BARPCManager closeConnectionsForView:self];
    }
}

-(void)clearSearchResultsAndHideFilters
{
    self.latestResult = nil;
    self.searchQuery = nil;
    [self.baSearchResultsViewController clearSearchResults];
    [self hideFilterButtons:YES adjustOffset:NO animated:NO];
    [self hideFilterDescriptionsBar];
    [self clearFilterDescriptionBarButtons];
    _isLargeFilterButtonsEnabled=NO;
    [self hideRevealFiltersButton];
    [self.loadingIndicator stopAnimating];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    //DLog(@"search cancelled");
//    NSString *str = searchBar.text;
//    [self.searchDisplayController setActive:NO animated:YES];
//    self.searchDisplayController.searchBar.text = str;
    if (searchBar.canResignFirstResponder) {
        [searchBar resignFirstResponder];
    }
}

#pragma mark - Initate Search
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	DLog(@"do search text: %@",searchBar.text);
    
    _isLargeFilterButtonsEnabled=NO;
    [self hideRevealFiltersButton];
    if (searchBar.canResignFirstResponder) {
        [searchBar resignFirstResponder];
    }
    
    [self.recentSearchesDataSource addSearchQuery:searchBar.text];
    
    [self performSearch:searchBar.text withUserFilters:@{}];
}

-(void)performSearch:(NSString*)searchText withUserFilters:(NSDictionary*)userFilters
{
    self.searchQuery = searchText;
    self.searchQueryUserFilter = userFilters;
    //[self.searchDisplayController setActive:NO animated:YES];
    //self.searchDisplayController.searchBar.text = self.searchQuery;
    self.searchOffset = 0;
    
    
    self.noResultsLabel.hidden = YES;
    self.performingSearchView.hidden=NO;
    [self.loadingIndicator startAnimating];
    self.startSearchView.hidden=YES;
    [self.baSearchResultsViewController clearSearchResults];
    [self clearFilterDescriptionBarButtons];
    _isLargeFilterButtonsEnabled=NO;
    [self hideRevealFiltersButton];
    [self hideFilterButtons:YES adjustOffset:NO animated:NO];
    [self hideFilterDescriptionsBar];
    self.filterButtonsHeight.constant = 0;
    
    //[self.filterDescriptionsBar setHidden:YES];
    //[self.filterButtonsContainer setHidden:YES];
    
    [BARPCManager closeConnectionsForView:self]; //cancel all previous requests
    
    NSMutableDictionary* combinedQueryFilter = [NSMutableDictionary dictionaryWithDictionary:self.searchQueryUserFilter];
    [combinedQueryFilter addEntriesFromDictionary:self.searchQueryLibrarianFilter];

    
    if ( ! isLibrarianAlmaSearchMore) {
    
        [BARPCManager searchAsyncFromView:self
                                    query:self.searchQuery
                                   filter:combinedQueryFilter //self.searchQueryFilter
                                    count:20
                                   offset:self.searchOffset
                              resultBlock:^(BASearchResult *result) {
                                  if([result.imf count] > 0 && [BALibrarySettings instance].isImfEnabled) {
#ifdef BA_IMF_BUILD
                                      [self.packageScrollViewContainer setHidden:NO];
                                      self.packagesHidden = NO;
                                      searchResultHasImfPackages = YES;
                                      
                                      [self.packageViewer setPackages:result.imf];
#endif
                                      
                                  } else {
                                      self.packagesHidden = YES;
                                      searchResultHasImfPackages = NO;
                                      [self.packageScrollViewContainer setHidden:YES];
                                  }
                                  [self showSearchResultsWithResults:result isFirstPage:YES isTypeFilteredSearch:NO];
                              }
                               errorBlock:^(int code, NSString *error) {
                                   DLog(@"search error: %@",error);
                                   [self showSearchErrorWithMessage:[NSString stringWithFormat:@"Søgningen kunne ikke gennemføres. %@",error]];
                               }
         ];
    } else {
#ifdef BA_LIBRARIAN_BUILD
        [LBRPCManager librarianSearchAsyncFromView:self
                                             query:self.searchQuery
                                             count:20
                                            offset:self.searchOffset
                                       resultBlock:^(BASearchResult *result) {
                                           searchResultHasImfPackages = NO;
                                           [self.packageScrollViewContainer setHidden:YES];
                                           
                                           [self showSearchResultsWithResults:result isFirstPage:YES isTypeFilteredSearch:NO];
                                           self.baSearchResultsViewController.tableView.contentInset = UIEdgeInsetsZero;
                                           
                                           /*test
                                            DLog(@"librarianSearchAsyncFromView result count: %d",result.count);
                                            for (BACollection* c in result.data) {
                                                for (BARecord* rec in c.records) {
                                                    DLog(@"%@ by %@",rec.title,[rec.creators count]>0 ? [rec.creators firstObject]  : @"(none)");
                                                }
                                            }*/
                                       }
                                        errorBlock:^(int errorCode, NSString *errorMessage) {
                                            DLog(@"ERROR: librarianSearchAsyncFromView code %d, %@",errorCode,errorMessage);
                                            [self showSearchErrorWithMessage:[NSString stringWithFormat:@"Søgningen kunne ikke gennemføres. %@",errorMessage]];
                                        }
         ];
#endif
        
    }
    
    self.searchOffset += 20;
}

-(void)externalPerformSearchWithSearchString:(NSString*)searchString withLibrarianFilters:(NSDictionary*)librarianFilters
{
    [self view];
    
    if ([searchString length]>0) {
        [self.searchBar setText:searchString];
    } else {
        for (NSArray* filterArray in [librarianFilters allValues]) {
            //first filter
            for (NSString* filter in filterArray) {
                [self.searchBar setText:filter];
                break;
            }
        }
    }
    
    self.searchQueryLibrarianFilter=librarianFilters;
    [self performSearch:searchString withUserFilters:@{}];
}

-(void)externalPerformAlmaSearchWithSearchString:(NSString *)searchString
{
    [self view];
    
    self.searchContentTopConstraint.constant = 0;
    self.filterButtonsHeight.constant = 0;
    self.packagesHidden = YES;
    self.largeFilterBarHidden = YES;
    
    if ([searchString length]>0) {
        [self.searchBar setText:searchString];
    }
    isLibrarianAlmaSearchMore = YES;
    self.searchQueryLibrarianFilter=@{};
    [self performSearch:searchString withUserFilters:@{}];
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    if ([BAPatronSettings instance].isUserAllowedLibrarianAccessForCurrentLibrary) {
        //special case for librarian mode
        [self.navigationController popViewControllerAnimated:YES];
        return NO;
        
    } else {
        // reset the shouldBeginEditing BOOL ivar to YES, but first take its value and use it to return it from the method call
        BOOL boolToReturn = shouldBeginEditing;
        shouldBeginEditing = YES;
        return boolToReturn;
    }
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES];
    
    if ([[BAUtils instance] iOSMajorVersion] >= 7) {
        //ios 7 code
        UIButton *cancelButton;
        if ([searchBar.subviews count]>0) {
            UIView *topView = searchBar.subviews[0];
            for (UIView *subView in topView.subviews) {
                if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
                    cancelButton = (UIButton*)subView;
                }
            }
            if (cancelButton) {
                [cancelButton setTitle:@"Annuller" forState:UIControlStateNormal];
            }
        }
    } else {
        //ios 6 code
        for (UIView *subView in searchBar.subviews){
            if([subView isKindOfClass:[UIButton class]]){
                [(UIButton*)subView setTitle:@"Annuller" forState:UIControlStateNormal];
            }
        }
    }
    
#ifdef HENRIK_RECENTSEARCHES_DEBUG
    //This is supposed to be an add-on
    [self.recentSearchesTableView setHidden:NO];
#endif
    
    [self hideRevealFiltersButton];
    [self.view layoutIfNeeded];
    /*
    [UIView animateWithDuration:0.2 delay:0 options:(UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear) animations:^{
        [self hideRevealFiltersButton];
    } completion:nil];
    */
    
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:NO];

#ifdef HENRIK_RECENTSEARCHES_DEBUG
    //This is suppose to be an add-on
    [self.recentSearchesTableView setHidden:YES];
#endif
    
    if (self.isLargeFilterButtonsEnabled) {
        [self showRevealFiltersButton];
    }
    [self.view layoutIfNeeded];
    
    
    
    // the reveal filters button must only be revealed when we know there are more than 3 facets
    /*
    if (self.isLargeFilterButtonsEnabled) {
        [UIView animateWithDuration:0.2
                              delay:0
                            options:(UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear)
                         animations:^{
                             [self showRevealFiltersButton];
                         }
                         completion:nil
         ];

    }
     */
}


#pragma mark -

-(void)showSearchResultsWithResults:(BASearchResult*)result isFirstPage:(BOOL)isFirstPage isTypeFilteredSearch:(BOOL)isTypeFiltered
{
    DLog(@"search result: %@",result)
    
    self.latestResult = result;
    
    [self.loadingIndicator stopAnimating];
    self.performingSearchView.hidden=YES;
    
    NSMutableArray* records = [NSMutableArray new];
    
    for (BACollection* collection in result.data) {
        for (BARecord* record in collection.records) {
            [records addObject:record];
        }
    }
    
    if (result.count>0) {
        [self.baSearchResultsViewController appendSearchRecords:records];
        [self fetchAvailabilityForSearchResults:records];
        [self fetchCoverUrlsForSearchResults:records];
        if (isFirstPage && !isTypeFiltered) {
            if ([result.facets count]>0) {
                BAFacet* facet1 = [result.facets objectAtIndex:0];
                if ([facet1.terms count]>=3) {
                    
                    if (RD_IS_IPHONE5) {
                        _isLargeFilterButtonsEnabled = YES;
                        self.largeFilterBarHidden = NO;
                    } else{
                        _isLargeFilterButtonsEnabled = NO;
                        self.largeFilterBarHidden = YES;
                    }
                    
                    
                    //[self showFilterButtons];
                    
                    BATerm* term1 = [facet1.terms objectAtIndex:0];
                    BATerm* term2 = [facet1.terms objectAtIndex:1];
                    BATerm* term3 = [facet1.terms objectAtIndex:2];
                    
                    UIImage* iconImage1 = [[BALibrarySettings instance] getIconForMaterialType:term1.term
                                                                             contextIdentifier:BATypeIconContextSearchFilterButton
                                                                                         color:[UIColor whiteColor]];
                    UIImage* iconImage2 = [[BALibrarySettings instance] getIconForMaterialType:term2.term
                                                                             contextIdentifier:BATypeIconContextSearchFilterButton
                                                                                         color:[UIColor whiteColor]];
                    UIImage* iconImage3 = [[BALibrarySettings instance] getIconForMaterialType:term3.term
                                                                             contextIdentifier:BATypeIconContextSearchFilterButton
                                                                                         color:[UIColor whiteColor]];
                    [self.largeFilterButton1 setImage:iconImage1 forState:UIControlStateNormal];
                    [self.largeFilterButton2 setImage:iconImage2 forState:UIControlStateNormal];
                    [self.largeFilterButton3 setImage:iconImage3 forState:UIControlStateNormal];
                    [self.packageAndFilterButtonsContainerView layoutIfNeeded];
                    
//                    self.largeFilterButton1.imageView.contentMode = UIViewContentModeScaleAspectFit;
//                    self.largeFilterButton2.imageView.contentMode = UIViewContentModeScaleAspectFit;
//                    self.largeFilterButton3.imageView.contentMode = UIViewContentModeScaleAspectFit;
                    
                    self.largeFilterButton1CountLabel.text = [NSString stringWithFormat:@"%d", term1.frequence];
                    self.largeFilterButton2CountLabel.text = [NSString stringWithFormat:@"%d", term2.frequence];
                    self.largeFilterButton3CountLabel.text = [NSString stringWithFormat:@"%d", term3.frequence];
                    

                } else {
                    
                    self.largeFilterBarHidden = YES;
                    _isLargeFilterButtonsEnabled=NO;
                }
                
                [self.baSearchResultsViewController.tableView setContentInset:UIEdgeInsetsMake(self.topBarHeight, 0, 0, 0)];
                [self.baSearchResultsViewController.tableView setContentOffset:CGPointMake(0, -self.topBarHeight)];
                self.filterButtonsHeight.constant = self.topBarHeight;
                if (self.topBarHeight > 0) {
                    [self showRevealFiltersButton];
                }
                
                //[self.filterButtonsContainer setHidden:NO];
                //[self.filterDescriptionsBar setHidden:NO];
                [self showFilterDescriptionsBar];
                [self hideFilterButtons:NO adjustOffset:YES animated:NO];
                
                filterDescriptionsBarButtons = [NSMutableArray new];
                filterDescriptionStrings = [NSMutableArray new];
                
                int cur_x = 10;
                cur_x += [self createNewFilterDescriptionButtonWithTerm:@"ALLE" count:result.count isSelected:NO atX:cur_x];
                [filterDescriptionStrings addObject:@""];
                cur_x += 5;
                
                
                for (BATerm* term in facet1.terms) {
                    CGFloat buttonWidth = [self createNewFilterDescriptionButtonWithTerm:term.term count:term.frequence isSelected:NO atX:cur_x];
                    [filterDescriptionStrings addObject:term.term];
                    cur_x += buttonWidth + 5;
                }
                
                [self selectFilterButton:[filterDescriptionsBarButtons objectAtIndex:0]];
                //self.filterDescriptionsContent.frame = CGRectMake(0, 0, cur_x, 42);
                //[self.searchFiltersScroller setContentSize:CGSizeMake(cur_x, 42)];
                self.filterDescriptionsContentWidth.constant = cur_x;
            }
        
           

        }
        if (isFirstPage) {
            [self hideFilterButtons:NO adjustOffset:YES animated:NO];
        }
        
    } else {
        [self.baSearchResultsViewController clearSearchResults];
        [self clearFilterDescriptionBarButtons];
        _isLargeFilterButtonsEnabled=NO;
        [self hideFilterButtons:YES adjustOffset:YES animated:NO];
        [self hideFilterDescriptionsBar];
        
        //self.noResultsLabel.hidden=NO;
        [self showSearchErrorWithMessage:@"Der blev desværre ikke fundet nogen materialer, der matcher din søgning."];
    }

}

-(CGFloat)createNewFilterDescriptionButtonWithTerm:(NSString*)term count:(int)count isSelected:(BOOL)isSelected atX:(CGFloat)cur_x
{
    UIButton* newbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (isSelected) {
        [newbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [newbutton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    } else {
        [newbutton setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.40] forState:UIControlStateNormal];
        [newbutton setTitleColor:[[UIColor grayColor] colorWithAlphaComponent:0.40] forState:UIControlStateHighlighted];
    }
    NSString* titletext = [term uppercaseString]; //[[NSString stringWithFormat:@"%@ (%d)",term, count] uppercaseString];
    [newbutton setTitle:titletext forState:UIControlStateNormal];
    if (isSelected ) {
        [newbutton.titleLabel setFont:BA_FONT_REGULAR(10)];
    } else {
        [newbutton.titleLabel setFont:BA_FONT_LIGHT(10)];
    }
    
    CGSize textrect = [titletext sizeWithFont:newbutton.titleLabel.font];
    CGFloat buttonWidth = textrect.width + 10;
    newbutton.frame = CGRectMake(cur_x, 3, buttonWidth, 30);
    [self.filterDescriptionsContent addSubview:newbutton];
    [newbutton addTarget:self action:@selector(filterButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [filterDescriptionsBarButtons addObject:newbutton];
    
    return buttonWidth;
}

-(void)selectFilterButton:(UIButton*)sel_button
{
    [sel_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sel_button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [sel_button.titleLabel setFont:BA_FONT_REGULAR(10)];
    
    CGRect sel_rect = sel_button.frame;
    CGFloat mid_x = sel_rect.origin.x + sel_rect.size.width/2.0;
    CGRect indicator_rect = self.filterDescriptionsSelectionIndicatorImage.frame;
    CGFloat indicator_width = indicator_rect.size.width;
    indicator_rect.origin.x = mid_x - indicator_width/2.0;
    
    [UIView animateWithDuration:0.5 animations:^{
        self.filterDescriptionsSelectionIndicatorImage.frame = indicator_rect;
    }];
    
    [self.filterDescriptionsScroller scrollRectToVisible:sel_rect animated:YES];
    
    
    for (UIButton* otherbutton in filterDescriptionsBarButtons) {
        if (otherbutton!=sel_button) {
            [otherbutton setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.60] forState:UIControlStateNormal];
            [otherbutton setTitleColor:[[UIColor grayColor] colorWithAlphaComponent:0.60] forState:UIControlStateHighlighted];
            [otherbutton.titleLabel setFont:BA_FONT_LIGHT(10)];
            
        }
    }

    NSUInteger button_index = [filterDescriptionsBarButtons indexOfObject:sel_button];
    if (button_index==0) {
        self.largeFilterButton1.imageView.alpha = 1;
        self.largeFilterButton2.imageView.alpha = 1;
        self.largeFilterButton3.imageView.alpha = 1;
        self.largeFilterButton1CountLabel.alpha = 1;
        self.largeFilterButton2CountLabel.alpha = 1;
        self.largeFilterButton3CountLabel.alpha = 1;
    } else if (button_index==1) {
        self.largeFilterButton1.imageView.alpha = 1;
        self.largeFilterButton2.imageView.alpha = 0.25;
        self.largeFilterButton3.imageView.alpha = 0.25;
        self.largeFilterButton1CountLabel.alpha = 1;
        self.largeFilterButton2CountLabel.alpha = 0.25;
        self.largeFilterButton3CountLabel.alpha = 0.25;
    } else if (button_index==2) {
        self.largeFilterButton1.imageView.alpha = 0.25;
        self.largeFilterButton2.imageView.alpha = 1;
        self.largeFilterButton3.imageView.alpha = 0.25;
        self.largeFilterButton1CountLabel.alpha = 0.25;
        self.largeFilterButton2CountLabel.alpha = 1;
        self.largeFilterButton3CountLabel.alpha = 0.25;
    } else if (button_index==3) {
        self.largeFilterButton1.imageView.alpha = 0.25;
        self.largeFilterButton2.imageView.alpha = 0.25;
        self.largeFilterButton3.imageView.alpha = 1;
        self.largeFilterButton1CountLabel.alpha = 0.25;
        self.largeFilterButton2CountLabel.alpha = 0.25;
        self.largeFilterButton3CountLabel.alpha = 1;
    } else {
        self.largeFilterButton1.imageView.alpha = 0.25;
        self.largeFilterButton2.imageView.alpha = 0.25;
        self.largeFilterButton3.imageView.alpha = 0.25;
        self.largeFilterButton1CountLabel.alpha = 0.25;
        self.largeFilterButton2CountLabel.alpha = 0.25;
        self.largeFilterButton3CountLabel.alpha = 0.25;
    }
}

-(IBAction)filterButtonClicked:(id)sender
{
    [self.baSearchResultsViewController clearSearchResults];
    self.noResultsLabel.hidden = YES;
    self.performingSearchView.hidden=NO;
    [self.loadingIndicator startAnimating];
    self.startSearchView.hidden=YES;

    [self hideFilterButtons:NO adjustOffset:YES animated:YES];
    
    NSUInteger button_index = [filterDescriptionsBarButtons indexOfObject:sender];
    if (button_index==NSNotFound) {
        //not in bar button list, so we check if it is one of the large filter icons
        if (sender==self.largeFilterButton1) {
            button_index=1;
        } else if (sender==self.largeFilterButton2) {
            button_index=2;
        } else if (sender==self.largeFilterButton3) {
            button_index=3;
        }
    }
    if (button_index!=NSNotFound && button_index<[filterDescriptionStrings count] && button_index<[filterDescriptionsBarButtons count]) {
        NSString* filtertext = [filterDescriptionStrings objectAtIndex:button_index];
        [self selectFilterButton:[filterDescriptionsBarButtons objectAtIndex:button_index]];
        
        if ([filtertext length]>0) {
            self.searchQueryUserFilter = @{[[BALibrarySettings instance] getDefaultMaterialTypeFilter]: @[filtertext]};
        } else {
            self.searchQueryUserFilter = @{}; //make a default "all" search
        }
        [BARPCManager closeConnectionsForView:self]; //cancel all pending requests
        self.searchOffset = 0;
        
        NSMutableDictionary* combinedQueryFilter = [NSMutableDictionary dictionaryWithDictionary:self.searchQueryUserFilter];
        [combinedQueryFilter addEntriesFromDictionary:self.searchQueryLibrarianFilter];
        
        [BARPCManager searchAsyncFromView:self
                                    query:self.searchQuery
                                   filter:combinedQueryFilter //self.searchQueryFilter
                                    count:20
                                   offset:self.searchOffset
                              resultBlock:^(BASearchResult *result) {
                                  [self showSearchResultsWithResults:result isFirstPage:NO isTypeFilteredSearch:NO];
                              }
                               errorBlock:^(int code, NSString *error) {
                                   DLog(@"search error: %@",error);
                                   [self showSearchErrorWithMessage:[NSString stringWithFormat:@"Søgningen kunne ikke gennemføres. %@",error]];
                                   [self.baSearchResultsViewController clearSearchResults];
                                   [self clearFilterDescriptionBarButtons];
                                   _isLargeFilterButtonsEnabled=NO;
                                   [self hideRevealFiltersButton];
                                   [self hideFilterButtons:YES adjustOffset:NO animated:NO];
                                   [self hideFilterDescriptionsBar];

                               }
         ];
        self.searchOffset+=20;
        
    }
   
}

-(void)showSearchErrorWithMessage:(NSString*)errorMessage
{
    [self.loadingIndicator stopAnimating];
    self.performingSearchView.hidden=YES;
    [self.baSearchResultsViewController clearSearchResults];
    self.noResultsLabel.hidden=NO;
    self.noResultsLabel.text = errorMessage;
    [self clearFilterDescriptionBarButtons];
    _isLargeFilterButtonsEnabled=NO;
    [self hideRevealFiltersButton];

}

-(void)clearFilterDescriptionBarButtons
{
    for (UIButton* b in filterDescriptionsBarButtons) {
        [b removeFromSuperview];
    }
    [filterDescriptionsBarButtons removeAllObjects];
    [self.filterDescriptionsScroller setContentOffset:CGPointZero animated:NO];
}

-(void)fetchAvailabilityForSearchResults:(NSArray*)records
{
    NSMutableArray* identifiers = [NSMutableArray new];
    
    for (BARecord* record in records) {
        [identifiers addObject:record.identifier];
    }

    [BARPCManager getAvailabilityAsyncFromView:self
                                   identifiers:identifiers
                            includeHoldingInfo:NO
                                   resultBlock:^(NSDictionary *result) {
                                       [self.baSearchResultsViewController appendAvailabilityRecords:result];
                                   }
                                    errorBlock:^(int errorCode, NSString *errorMessage) {
                                        DLog(@"error fetching availability %d %@",errorCode, errorMessage);
                                    }];
    

}

-(void)fetchCoverUrlsForSearchResults:(NSArray*)records
{
    NSMutableArray* identifiers = [NSMutableArray new];
    
    for (BARecord* record in records) {
        [identifiers addObject:record.identifier];
    }
    
    [[BACoverUrlAndAvailabilityMemoryCache instance] fetchCoverUrlsForIdentifiers:identifiers];
    
    /* old code
    [BARPCManager getCoverUrlsAsyncFromView:self
                            coverUrlQueries:identifiers
                                resultBlock:^(NSDictionary* result) {
                                    [self.baSearchResultsViewController appendCoverUrls:result];
                                }
                                 errorBlock:^(int errorCode, NSString *errorMessage) {
                                     DLog(@"error fetching coverurls %d %@",errorCode, errorMessage);
                                 }];
     */

}

- (void)somewhereElseClicked:(id)sender
{
    /*
	if ([self.theSearchBar canResignFirstResponder]) {
		[self.theSearchBar resignFirstResponder];
	}*/
}



-(void)hideRevealFiltersButton
{
    self.searchBarTralingSpace.constant = 0;
    [self.view layoutIfNeeded];
}

-(void)showRevealFiltersButton
{
    self.searchBarTralingSpace.constant = self.revealFilterButtonsButtonWidth.constant;
    
    [self.view layoutIfNeeded];

}


#pragma mark - BASearchResultsViewController helper metrods

-(BOOL)hasMoreResults{
    return self.latestResult.more;
}

-(void)loadMoreResults
{
    NSMutableDictionary* combinedQueryFilter = [NSMutableDictionary dictionaryWithDictionary:self.searchQueryUserFilter];
    [combinedQueryFilter addEntriesFromDictionary:self.searchQueryLibrarianFilter];

    if (self.searchQuery != nil) {
        if ( ! isLibrarianAlmaSearchMore) {

        [BARPCManager searchAsyncFromView:self
                                    query:self.searchQuery
                                   filter:combinedQueryFilter  //self.searchQueryFilter
                                    count:20
                                   offset:self.searchOffset
                              resultBlock:^(BASearchResult *result) {
                                  [self showSearchResultsWithResults:result isFirstPage:NO isTypeFilteredSearch:NO];
                              }
                               errorBlock:^(int code, NSString *error) {
                                   DLog(@"search error: %@",error);
                                   self.searchOffset-=20;
                                   [self.baSearchResultsViewController loadMoreResultsFailed];
                               }
         ];
            
        } else {
#ifdef BA_LIBRARIAN_BUILD
            [LBRPCManager librarianSearchAsyncFromView:self
                                                 query:self.searchQuery
                                                 count:20
                                                offset:self.searchOffset
                                           resultBlock:^(BASearchResult *result) {
                                               [self showSearchResultsWithResults:result isFirstPage:NO isTypeFilteredSearch:NO];
                                           }
                                            errorBlock:^(int code, NSString *error) {
                                                DLog(@"search error: %@",error);
                                                self.searchOffset-=20;
                                                [self.baSearchResultsViewController loadMoreResultsFailed];
                                            }
             ];
#endif
        }
        
        self.searchOffset+=20;
    }

}

- (void)hideFilterButtons:(BOOL)hide adjustOffset:(BOOL)adjust animated:(BOOL)animated
{
    [self hideFilterButtons:hide];
    
    return;
    
    /* FIXME: old code?
    currentInset = self.baSearchResultsViewController.tableView.contentInset;
    currentOffset= self.baSearchResultsViewController.tableView.contentOffset;
    newOffset = currentOffset;
    if (hide) {
        _isShowingLargeFilterButtons = NO;
        [self.revealFiltersButton setSelected:NO];
        self.filterButtonsHeight.constant = 0;
        currentInset.top = 34;
        if(searchResultHasImfPackages) {
            newOffset.y += 196;
        } else {
            newOffset.y += 64;
        }
    } else if(!self.isLargeFilterButtonsEnabled){
        _isShowingLargeFilterButtons = NO;
        [self.revealFiltersButton setSelected:NO];
        self.filterButtonsHeight.constant = 0;
        currentInset.top = 34;
        if(searchResultHasImfPackages) {
            newOffset.y -= 196;
        } else {
            newOffset.y -= 64;
        }
    }else {
        _isShowingLargeFilterButtons = YES;
        [self.revealFiltersButton setSelected:YES];
        if(searchResultHasImfPackages) {
            self.filterButtonsHeight.constant = 196; // bvd
            currentInset.top = 34 + 196; // bvd
            newOffset.y -= 196; // bvd
        } else {
            self.filterButtonsHeight.constant = 64;
            currentInset.top = 34 + 64;
            newOffset.y -= 64;
        }
    }
    
    if (animated) {
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            [self.baSearchResultsViewController.tableView setContentInset:currentInset];
            if (adjust && newOffset.y + currentInset.top >= -34) {
                [self.baSearchResultsViewController.tableView setContentOffset:newOffset];
            }
           [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
    } else{
        [self.baSearchResultsViewController.tableView setContentInset:currentInset];
        if (adjust && newOffset.y + currentInset.top >= -34) {
            [self.baSearchResultsViewController.tableView setContentOffset:newOffset];
        }
    }
    */
}

-(void)showFilterDescriptionsBar
{
    
    self.filterDescriptionsHeight.constant = 42;
    [self.view layoutIfNeeded];
}

-(void)hideFilterDescriptionsBar
{
    
    self.filterDescriptionsHeight.constant = 0;
    [self.view layoutIfNeeded];

}

- (IBAction)revealFiltersButtonClicked:(UIButton*)sender {
//    return;
    
    if (!self.isShowingLargeFilterButtons) {
        [self hideFilterButtons:NO adjustOffset:YES animated:YES];
    } else {
        [self hideFilterButtons:YES adjustOffset:YES animated:YES];

    }
}

-(BASpecialNavigationBarConfiguration)getRequestedSpecialNavigationBarConfiguration
{
    return BASpecialNavigationBarConfigurationCompletelyColored;
}

#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}


#pragma mark - Keyboard Notification handling

- (void)addKeyboardObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeKeyboardObserver{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    
    CGRect keyboardFrame = [kbFrame CGRectValue];
    
    CGFloat height = keyboardFrame.size.height;
    
    if (self.tabBarController.tabBar != nil) {
        height -= self.tabBarController.tabBar.frame.size.height;
    }
    if (self.recentSearchesBottomSpace.constant != height) {
        //We wait until the keyboard is visible to change the layoutconstraint
        self.recentSearchesBottomSpace.constant = height;
        self.activityViewBottomSpace.constant = height;
        [UIView animateWithDuration:animationDuration delay:0.1 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            [self.view layoutIfNeeded];
        } completion:nil];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
//            self.recentSearchesBottomSpace.constant = height;
//            self.activityViewBottomSpace.constant = height;
//            [self.view layoutIfNeeded];
//        });
        
    }
    
    /* this breaks constraints on 3.5" phone
    self.startSearchViewBottomSpaceConstraint.constant = height;
    [self.view setNeedsUpdateConstraints];
    [UIView animateWithDuration:0.33
                     animations:^{
                         [self.view layoutIfNeeded];
                     }
     ];
     */
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    self.recentSearchesBottomSpace.constant = 0;
    self.activityViewBottomSpace.constant = 0;
    [UIView animateWithDuration:animationDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];
    
    /*
    self.startSearchViewBottomSpaceConstraint.constant = 0;
    [self.view setNeedsUpdateConstraints];
    [UIView animateWithDuration:0.33
                     animations:^{
                         [self.view layoutIfNeeded];
                     }
     ];
     */
}

#pragma mark BARecentSearchesDelegate

-(void)didSelectRecentSearchQuery:(NSString *)query{
    [self.searchBar setText:query];
    [self searchBarSearchButtonClicked:self.searchBar];
}

#pragma mark show/hide filter buttons

-(CGFloat)topBarHeight{
    
    return self.packageAndFilterButtonsContainerView.frame.size.height;
//
//    CGFloat height = 0;
//    height += self.packageViewContainerHeight.constant;
//    height += self.filterButtonsContainerHeight.constant;
//    return height;
}

-(void)setLargeFilterBarHidden:(BOOL)largeFilterBarHidden{
    _largeFilterBarHidden = largeFilterBarHidden;
    if (largeFilterBarHidden) {
        self.filterButtonsContainerHeight.constant = 0;
    } else{
        self.filterButtonsContainerHeight.constant = 64;
    }
    [self.packageAndFilterButtonsContainerView layoutIfNeeded];
}

-(void)setPackagesHidden:(BOOL)packagesHidden{
    _packagesHidden = packagesHidden;
    if (packagesHidden) {
        self.packageViewContainerHeight.constant = 0;
    } else{
        self.packageViewContainerHeight.constant = 132;
    }
    [self.packageAndFilterButtonsContainerView layoutIfNeeded];
}

-(void)setIsShowingLargeFilterButtons:(BOOL)isShowingLargeFilterButtons{
    if (_isShowingLargeFilterButtons == isShowingLargeFilterButtons) {
        return;
    }
    _isShowingLargeFilterButtons = isShowingLargeFilterButtons;
    
    [self.revealFiltersButton setSelected:isShowingLargeFilterButtons];
    [self.packageAndFilterButtonsContainerView layoutIfNeeded];
}

- (void)hideFilterButtons:(BOOL)hide
{
    mIgnoreScrolling = YES;
    mIsDecelerating = NO;
    mIsDragging = NO;
//    [self.baSearchResultsViewController.tableView setContentOffset:self.baSearchResultsViewController.tableView.contentOffset animated:NO];

    BOOL adjustOffset = NO;
    CGPoint newContentOffset = CGPointMake(0, 0);
    CGFloat adjustedOffset = self.baSearchResultsViewController.tableView.contentOffset.y + self.baSearchResultsViewController.tableView.contentInset.top;
    CGFloat topBarHeight = self.topBarHeight;
    if (hide) {
        self.isShowingLargeFilterButtons = NO;
        self.filterButtonsHeight.constant = 0;
        
        
        if (adjustedOffset <= topBarHeight) {
            adjustOffset = YES;
            //            newContentOffset.y = -topBarHeight;
        }
        
    } else{
        self.isShowingLargeFilterButtons = YES;
        self.filterButtonsHeight.constant = self.topBarHeight;
        if (adjustedOffset == topBarHeight) {
            adjustOffset = YES;
            newContentOffset.y = -topBarHeight;
        }
    }
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        if (adjustOffset) {
            self.baSearchResultsViewController.tableView.contentOffset = newContentOffset;
        }
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark UIScrollViewDelegate
//Notice that not all UIScrollViewDelegate are supported as they are forewarded from BASearchResultsViewController!

BOOL mIsDragging = NO;
BOOL mIsDecelerating = NO;
BOOL mIgnoreScrolling = NO;
BOOL mIsScrollingToTop = NO;
CGFloat mInitialScrollOffset;
//CGFloat mFilterHeight = 196;
CGFloat mInitialFilterHeight = 0;

-(BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView{
    mIsScrollingToTop = YES;
    if (self.filterButtonsHeight.constant > 0) {
        mInitialScrollOffset = scrollView.contentOffset.y + scrollView.contentInset.top;
    } else{
        mInitialScrollOffset = 0;
    }
    return YES;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (!mIsDecelerating) {
        if (self.filterButtonsHeight.constant > 0) {
            mInitialScrollOffset = scrollView.contentOffset.y + scrollView.contentInset.top;
        } else{
            mInitialScrollOffset = 0;
        }
    }
    
    mIgnoreScrolling = NO;
    mIsDragging = YES;
    mIsDecelerating = NO;
    mIsScrollingToTop = NO;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.baSearchResultsViewController.searchResultCount == 0 || isLibrarianAlmaSearchMore) {
        return;
    }
    CGFloat adjustedOffset = scrollView.contentOffset.y + scrollView.contentInset.top;
    CGFloat topBarHeight = self.topBarHeight;
    if (mIgnoreScrolling && !(adjustedOffset <= topBarHeight)) {
        return;
    }
    
    
    
    CGFloat newHeight = 0;
    
    if (self.filterButtonsHeight.constant-adjustedOffset != 0 && mInitialScrollOffset > 0) {
        adjustedOffset -= mInitialScrollOffset;
    }
    
    if (adjustedOffset <= topBarHeight) {
        newHeight = topBarHeight-adjustedOffset;
        if (newHeight < 0) {
            newHeight = 0;
        } else if (newHeight > self.topBarHeight){
            newHeight = topBarHeight;
        }
    }
    self.isShowingLargeFilterButtons = (newHeight == 0 ? NO: YES);
    
    self.filterButtonsHeight.constant = newHeight;
//    DLog(@"Offset: %f - Height: %f  - Initial height: %f", adjustedOffset, newHeight, mInitialFilterHeight);
}

-(void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
    mIsScrollingToTop = NO;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    mIsDecelerating = NO;
    if (!mIsDragging) {
        [self scrollViewStoppedScrolling:scrollView];
    }
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
   mIsDragging = NO;
    if (decelerate) {
        mIsDecelerating = YES;
    } else{
        [self scrollViewStoppedScrolling:scrollView];
    }
}

- (void)scrollViewStoppedScrolling:(UIScrollView *)scrollView
{
    if (mIsScrollingToTop) {
        return;
    }
    mInitialScrollOffset = 0;
    CGFloat topBarHeight = self.topBarHeight;
    CGFloat newHeight = 0;
    if (self.filterButtonsHeight.constant < (topBarHeight/2)) {
        [self hideFilterButtons:YES];
        newHeight = 0;
    } else{
        [self hideFilterButtons:NO];
        newHeight = topBarHeight;
    }

}

@end
